package com.zrrd.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author WanJl
 * @version 1.0
 * @title AuthorizeFilter
 * @description
 * @create 2024/7/18
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求的请求头的所有参数
        //MultiValueMap<String, String> params = exchange.getRequest().getHeaders();
        //1.获取请求的所有参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();

        //2.获取authorization参数
        String authorization = params.getFirst("authorization");
        System.out.println(authorization);
        //3.进行校验
        //if (authorization.equals("admin"))
        if ("admin".equals(authorization)) {
            //放行
            return chain.filter(exchange);
        }
        //4.拦截
        //4.1 禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        //结束
        return exchange.getResponse().setComplete();
    }
}
